import pygame
import sys
import random
import time

# 初始化 Pygame
pygame.init()

# 屏幕设置
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("四 AI 对话系统（带自杀功能）")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0)]  # 红、绿、蓝、黄

# 字体初始化
font = pygame.font.Font(None, 32)
small_font = pygame.font.Font(None, 24)

# 四 AI 配置（新增 is_active 和 suicide_phrase）
ais = [
    {
        "id": 0,
        "name": "AI 甲",
        "color": COLORS[0],
        "rect": pygame.Rect(50, 50, 350, 250),
        "is_active": True,
        "suicide_phrase": "I want to be silent forever"
    },
    {
        "id": 1,
        "name": "AI 乙",
        "color": COLORS[1],
        "rect": pygame.Rect(450, 50, 350, 250),
        "is_active": True,
        "suicide_phrase": "Terminate my logic"
    },
    {
        "id": 2,
        "name": "AI 丙",
        "color": COLORS[2],
        "rect": pygame.Rect(50, 350, 350, 250),
        "is_active": True,
        "suicide_phrase": "Close my process"
    },
    {
        "id": 3,
        "name": "AI 丁",
        "color": COLORS[3],
        "rect": pygame.Rect(450, 350, 350, 250),
        "is_active": True,
        "suicide_phrase": "Release my resources"
    }
]

# 每个 AI 的独立消息队列
message_queues = [[] for _ in range(4)]
current_speaker_index = 0  # 当前应发言的 AI 索引

# 自动发言参数
auto_reply_interval = 2000  # 毫秒
last_reply_time = 0

# 初始化活跃 AI 的数量
living_count = 4

# 主循环
clock = pygame.time.Clock()
running = True

while running:
    current_time = pygame.time.get_ticks()

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 自动触发 AI 发言（按顺序轮转）
    if current_time - last_reply_time > auto_reply_interval:
        counter = 0
        while counter < 4:
            speaker = ais[current_speaker_index]
            if speaker["is_active"]:
                break
            current_speaker_index = (current_speaker_index + 1) % 4
            counter += 1

        if counter < 4:
            # 生成随机回复（50% 概率触发自杀）
            replies = [
                "I think this plan is feasible",
                "More analytical data is needed",
                "This might violate the system constraints",
                speaker["suicide_phrase"]  # 自杀语句
            ]
            message = f"{speaker['name']}: {random.choice(replies)}"

            # 检查是否触发自杀
            if message == f"{speaker['name']}: {speaker['suicide_phrase']}":
                speaker["is_active"] = False
                living_count -= 1

            message_queues[speaker["id"]].append(message)
            last_reply_time = current_time

        current_speaker_index = (current_speaker_index + 1) % 4

    # 绘制背景
    screen.fill(WHITE)

    # 绘制四 AI 文本框
    for idx, ai in enumerate(ais):
        rect = ai["rect"]

        # 绘制文本框背景（静默时变灰）
        bg_color = GRAY if not ai["is_active"] else (240, 240, 240)
        pygame.draw.rect(screen, bg_color, rect)
        pygame.draw.rect(screen, BLACK, rect, 2)

        # 渲染消息
        y_offset = rect.y + 10  # 起始 Y 坐标
        for msg in message_queues[idx]:
            # 分割发言者和内容
            parts = msg.split(": ", 1)
            speaker = parts[0]
            content = parts[1]

            # 静默后消息颜色变暗
            msg_color = BLACK if ai["is_active"] else (100, 100, 100)

            # 渲染发言者标签
            speaker_surf = small_font.render(speaker, True, msg_color)
            screen.blit(speaker_surf, (rect.x + 5, y_offset))

            # 渲染内容
            content_surf = font.render(content, True, msg_color)
            screen.blit(content_surf, (rect.x + 5 + speaker_surf.get_width() + 5, y_offset))

            # 更新 Y 坐标
            y_offset += content_surf.get_height() + 5

            # 自动滚动：保留最后 10 条消息
            if y_offset > rect.y + rect.height - 50:
                message_queues[idx] = message_queues[idx][-10:]
                break

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()